import React, { useEffect, useRef } from "react";
import { Form, Input, Button } from "antd";
import "./index.less";

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 }
};

function ResetPs(props) {

  const formRef = useRef({
    oldPs: '',
    newPs: '',
    newPs2: ''
  });

  const onFinish = values => {
    props.onOk(values);
    formRef.current.resetFields();
  };

  const onCancel = () => {
    props.onCancel();
    formRef.current.resetFields();
  };

  useEffect(() => {
    formRef.current.setFieldsValue({
      oldPs: '',
      newPs: '',
      newPs2: ''
    })
  });

  return (
    <Form
      {...layout}
      ref={formRef}
      name='control-hooks'
      onFinish={onFinish}
      initialValues={{
        oldPs: '',
        newPs: '',
        newPs2: ''
      }}
    >
      <Form.Item
        name='oldPs'
        label='旧密码'
        rules={[
          { required: true, whitespace: true, message: "请请入旧密码!" },
          { min: 2, message: "密码至少2位" },
          { max: 30, message: "密码最多30位" }
        ]}
      >
        <Input type="password" placeholder='请请入旧密码' />
      </Form.Item>
      <Form.Item
        name='newPs'
        label='新密码'
        rules={[
          { required: true, whitespace: true, message: "请请入新密码!" },
          { min: 2, message: "密码至少2位" },
          { max: 30, message: "密码最多30位" }
        ]}
      >
        <Input type="password" placeholder='请请入新密码' />
      </Form.Item>
      <Form.Item
        name='newPs2'
        label='确认新密码'
        rules={[
          {
            required: true,
            message: '请再次输入新密码',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('newPs') === value) {
                return Promise.resolve();
              }

              return Promise.reject(new Error('再次输入的密码与新密码不一致'));
            },
          }),
        ]}
      >
        <Input type="password" placeholder='请再次输入新密码' />
      </Form.Item>
      <Form.Item {...tailLayout}>
        <Button type='primary' htmlType='submit'>
          确定
        </Button>
        <Button
          htmlType='button'
          onClick={onCancel}
          className='cancelBtn'
        >
          取消
        </Button>
      </Form.Item>
    </Form>
  );
}

export default ResetPs;
